// ignore_for_file: must_be_immutable

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:happy_elf_app/apis/home.dart';
import 'package:happy_elf_app/apis/user.dart';
import 'package:happy_elf_app/store/config.dart';
import 'package:happy_elf_app/store/home.dart';
import 'package:happy_elf_app/utils/adaption.dart';
import 'package:happy_elf_app/utils/color.dart';
import 'package:happy_elf_app/utils/globalKey.dart';
import 'package:happy_elf_app/views/Home/track/components/moodDialog.dart';
import 'package:happy_elf_app/views/Home/track/components/tipModal.dart';

class Tracking extends StatefulWidget {
  // final VoidCallback callBack;
  Function callBack;

  Tracking({super.key, required this.callBack});

  @override
  State<Tracking> createState() => _TrackingState();
}

final HomeDataProvider = Provider.of<HomeData>(
  Global.navigatorKey.currentContext!,
  listen: false,
);

class _TrackingState extends State<Tracking>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  // int progress = 0; // 任务进度 默认是0
  bool isOver = false; // 是否已经完成
  List dataList = [];
  Map activeTask = {}; //选中的
  int task = 0; // 当前任务
  late Map<int, Map<int, TextEditingController>> _controllers;
  late Map<int, Map<int, FocusNode>> _focusNodes;
  bool isNeedRemind = false;
  Timer? _pollingTimer; // 定时器
  Map enterTimes = {};
  int durationSec = 0; // 秒数
  double sliderValue = 4.0; // 初始值设为4

  @override
  void initState() {
    super.initState();
    enter('任务追踪');
    getWeek();
    startPolling();
    _controller = AnimationController(vsync: this);
  }

  @override
  void dispose() {
    _controller.dispose();
    _focusNodes.forEach((taskIndex, subNodes) {
      subNodes.forEach((subIndex, node) => node.dispose());
    });
    _controllers.forEach((taskIndex, subControllers) {
      subControllers.forEach((subIndex, controller) => controller.dispose());
    });
    leave('任务追踪');
    super.dispose();
  }

  int progress() {
    int count = 0;
    if (dataList.isNotEmpty) {
      for (var step in dataList[task]['stepList']) {
        if (step['status'] == 2) {
          count += 1;
        }
      }
    }
    // print('111-------$count');
    // print('111-------${310 / (dataList[task]['stepList'].length) * count}');
    return count;
  }

  // 页面进入
  void enter(String pageName) {
    durationSec = DateTime.now().millisecondsSinceEpoch;
    _sendEvent(pageName, "enter");
  }

  // 页面离开
  void leave(String pageName) {
    if (durationSec != 0) {
      final time =
          ((DateTime.now().millisecondsSinceEpoch - durationSec)).round();
      _sendEvent(pageName, "leave", time: time);
    }
  }

  Future<void> _sendEvent(String pageName, String type, {int? time}) async {
    Map data = {
      "pageName": pageName,
      "eventType": type,
      if (time != null) "duration": time
    };
    var res = await User().report(data);
    print('上报时间$res');
    if (res['code'] == 200) {}
  }

  // 获取是否需要提交情绪报告
  void getWeek() async {
    String targetId = HomeDataProvider.target['id'].toString();
    var res = await Home().needRemind(targetId);
    if (res['code'] == 200) {
      isNeedRemind = res['data']['needRemind'];
      setState(() {});
      print('resweek${res['data']}');
    }
  }

  void startPolling() {
    EasyLoading.show(status: '加载中...');
    // 立即执行一次查询（可选，避免等待第一个2秒）
    getMoodReport();

    // 启动定时器，每2秒执行一次
    _pollingTimer = Timer.periodic(const Duration(seconds: 2), (timer) {
      getMoodReport();
    });
  }

  // 获取完整的任务
  void getMoodReport() async {
    String targetId = HomeDataProvider.target['id'].toString();
    var res = await Home().getAiTask(targetId);
    if (res['code'] == 200) {
      print('resmood${res['data']}');
      dataList = res['data']['taskList'];
      if (_pollingTimer != null) {
        _pollingTimer!.cancel();
        _pollingTimer = null;
      }
      EasyLoading.dismiss();
      _initControllers();
      setState(() {});
    }
  }

  // 提交步骤
  void submit(check, _sliderValue, item) async {
    Map data = {
      "stepId": item['id'],
      "feeling": _sliderValue as num,
      "feelingDescription": check
    };
    var res = await Home().overStep(data);
    if (res['code'] == 200) {
      Navigator.of(context).pop();
      print('submit${res['data']}');
      // activeTask['status'] = 2;
      getMoodReport();
      setState(() {});
    }
  }

  // 放弃
  void giveStep(item, subIndex) async {
    print('giveStepitem${item}');
    Map data = {
      "stepId": item['id'],
    };
    var res = await Home().giveStep(data);
    if (res['code'] == 200) {
      print('giveStep${res['data']}');
      dataList[task]['stepList'][subIndex]['giveUpCount'] =
          res['data']['giveUpCount'];
      // if (res['data']['giveUpCount'] == 3) {/
      // ignore: use_build_context_synchronously
      tipModal.init(
          item: {...item, 'img': res['data']['imageUrl']},
          callBack: () {
            Navigator.of(context).pop();
          },
          context: context);
      // }
      setState(() {});
    }
  }

  // 初始化所有子任务的控制器
  void _initControllers() {
    _controllers = {};
    _focusNodes = {};

    for (int taskIndex = 0; taskIndex < dataList.length; taskIndex++) {
      final task = dataList[taskIndex];
      final subTasks = task['stepList'] as List;
      _controllers[taskIndex] = {};
      _focusNodes[taskIndex] = {};

      for (int subIndex = 0; subIndex < subTasks.length; subIndex++) {
        final subTask = subTasks[subIndex];
        _controllers[taskIndex]![subIndex] = TextEditingController(
          text: subTask['name'] ?? '',
        );
        // 初始化焦点节点并添加监听
        final focusNode = FocusNode();
        focusNode.addListener(() {
          if (focusNode.hasFocus) {
            // 输入框获得焦点时，更新选中状态
            setState(() {
              activeTask = subTask;
            });
          }
        });
        _focusNodes[taskIndex]![subIndex] = focusNode;
      }
    }
  }

  Widget headTitle() {
    return Container(
      width: 350,
      height: 40,
      decoration: BoxDecoration(
          color: hexColor('#E9614D'), borderRadius: BorderRadius.circular(20)),
      child: GestureDetector(
          child: Padding(
        padding: EdgeInsets.symmetric(vertical: 4.px, horizontal: 26.px),
        child: Row(
          children: [
            Expanded(
              child: Row(
                children: [
                  task > 0
                      ? GestureDetector(
                          onTap: () {
                            task -= 1;
                            setState(() {});
                          },
                          child: Image.asset(
                            'lib/assets/images/home/track/arrow_back.png',
                            width: 24,
                            height: 24,
                          ),
                        )
                      : SizedBox(width: 24),
                  Image.asset(
                    'lib/assets/images/home/track/paintbrush.png',
                    width: 24,
                    height: 24,
                  ),
                  SizedBox(width: 24.px),
                  SizedBox(
                    width: 188,
                    child: Text(
                      '任务${task + 1}：${dataList.isNotEmpty ? (dataList[task]['name'] ?? '') : ''}',
                      style: TextStyle(color: Colors.white),
                      overflow: TextOverflow.ellipsis,
                      maxLines: 1,
                      softWrap: false,
                    ),
                  )
                ],
              ),
            ),
            Text('${task + 1}/${dataList.length}',
                style: TextStyle(color: Colors.white)),
            SizedBox(width: 6),
            task < dataList.length - 1
                ? GestureDetector(
                    onTap: () {
                      task += 1;
                      setState(() {});
                    },
                    child: Image.asset(
                      'lib/assets/images/home/track/arrow_next.png',
                      width: 24,
                      height: 24,
                    ),
                  )
                : SizedBox(width: 24)
          ],
        ),
      )),
    );
  }

  Widget contentBuild(int taskIndex, int subIndex, Map item) {
    print('Flexiblez-----${item}');
    int progress = item['giveUpCount'] ?? 0;
    print('${progress / 3}');
    int gress = ((progress / 3) * 100).round();
    return GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          if (item['giveUpCount'] != null) return;
          if (item['status'] == 2) return;
          // 点击任务项时，请求焦点并更新选中状态
          setState(() {
            activeTask = item;
          });
          _focusNodes[taskIndex]![subIndex]!.requestFocus();
        },
        child: Container(
          width: 309,
          margin: const EdgeInsets.only(top: 10),
          padding: const EdgeInsets.all(12),
          decoration: ShapeDecoration(
            color: item['giveUpCount'] != null && item['giveUpCount'] > 0
                ? hexColor('#F3F3F3')
                : activeTask == item
                    ? const Color.fromRGBO(255, 213, 213, 0.27)
                    : const Color.fromRGBO(255, 255, 255, 0.9),
            shape: RoundedRectangleBorder(
              side: BorderSide(
                width: 1,
                color: item['giveUpCount'] != null
                    ? const Color.fromRGBO(0, 0, 0, 0.2)
                    : activeTask == item
                        ? const Color(0xFFFFB6AC)
                        : const Color.fromRGBO(0, 0, 0, 0.2),
              ),
              borderRadius: BorderRadius.circular(10),
            ),
          ),
          child: Column(
            children: [
              Focus(
                onFocusChange: (hafocus) async {
                  var value = _controllers[taskIndex]![subIndex];
                  print('value--${value!.text}---task--$task');
                  if (!hafocus) {
                    Map data = {"stepId": activeTask['id'], "name": value.text};
                    // 失去焦点 更改内容
                    var res = await Home().updateStep(data);
                    print(res);
                  }
                },
                child: TextField(
                  controller: _controllers[taskIndex]![subIndex],
                  focusNode: _focusNodes[taskIndex]![subIndex],
                  // 核心：设置为多行模式并自动换行
                  maxLines: null,
                  // maxLength: 40,
                  style: TextStyle(
                    fontSize: 14,
                    color: item['status'] == 2
                        ? Color.fromRGBO(38, 38, 38, 0.4)
                        : Color(0xFF333333),
                  ),
                  decoration: const InputDecoration(
                    border: InputBorder.none,
                    hintText: '请输入任务内容',
                    hintStyle: TextStyle(
                      color: Color(0xFF999999),
                      fontSize: 14,
                    ),
                    contentPadding: EdgeInsets.zero,
                    isDense: true,
                    // 移除默认的滚动条
                    isCollapsed: true,
                  ),
                  onChanged: (value) {
                    // 更新数据中的标题
                    item['name'] = value;
                    // 如果是当前选中项，同步更新
                    if (activeTask == item) {
                      setState(() {
                        activeTask = {...item}; // 创建新对象触发更新
                      });
                    }
                  },
                ),
              ),
              SizedBox(height: 16),
              item['giveUpCount'] == null
                  ? Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        item['status'] == 2
                            ? Image.asset(
                                'lib/assets/images/home/track/status-0.png',
                                width: 32,
                                height: 32)
                            : Expanded(
                                child: Row(
                                mainAxisAlignment: MainAxisAlignment.end,
                                children: [
                                  GestureDetector(
                                    child: Image.asset(
                                        'lib/assets/images/home/track/duihao.png',
                                        width: 26,
                                        height: 26),
                                    onTap: () {
                                      // 打开情绪弹窗
                                      moodModel.init(
                                          callBack: (check, _sliderValue) {
                                            submit(check, _sliderValue, item);
                                          },
                                          context: context);
                                    },
                                  ),
                                  SizedBox(width: 4),
                                  GestureDetector(
                                    child: Image.asset(
                                        'lib/assets/images/home/track/chahao.jpg',
                                        width: 26,
                                        height: 26),
                                    onTap: () {
                                      giveStep(item, subIndex);
                                    },
                                  )
                                ],
                              ))
                      ],
                    )
                  : Container(
                      height: 40,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          SliderTheme(
                            data: SliderThemeData(
                              trackHeight: 10.0,
                              activeTrackColor: hexColor('#e9614d'),
                              inactiveTrackColor: Colors.white, // 底色白色
                              // 隐藏刻度节点
                              activeTickMarkColor: Colors.transparent,
                              inactiveTickMarkColor: Colors.transparent,
                              thumbColor: Colors.white,
                              // 使用带阴影的自定义滑块
                              thumbShape: const CustomRectangularThumbShape(
                                width: 10.0,
                                height: 18.0,
                              ),
                              // 使用带阴影的轨道
                              trackShape: const ShadowedRectangularTrackShape(),
                              overlayColor: Colors.transparent,
                              showValueIndicator: ShowValueIndicator.never,
                            ),
                            child: Slider(
                              value: sliderValue,
                              min: 0,
                              max: 100,
                              divisions: 100,
                              label: null,
                              onChanged: (double value) {
                                setState(() {
                                  sliderValue = value;
                                });
                                print('当前进度：$sliderValue');
                                if (value == 100) {
                                  // 为100时 完成任务
                                  moodModel.init(
                                      callBack: (check, _sliderValue) {
                                        submit(check, _sliderValue, item);
                                      },
                                      context: context);
                                }
                              },
                            ),
                          ),
                          Container(
                            width: 38,
                            height: 38,
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                                color: hexColor('#e9614d'),
                                borderRadius: BorderRadius.circular(20)),
                            child: Text(
                              '${sliderValue.round()}%',
                              style: TextStyle(
                                  color: hexColor('#ffffff'), fontSize: 14),
                            ),
                          )
                        ],
                      ),
                    )
            ],
          ),
        ));
  }

  Widget buttonBuild(String text, Function callback) {
    return GestureDetector(
      child: Container(
        width: 147,
        height: 32,
        padding: const EdgeInsets.symmetric(horizontal: 9.15, vertical: 6.10),
        decoration: ShapeDecoration(
          color: text == '分享' ? Color(0xFFE9614D) : Colors.white,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(17.24),
          ),
          shadows: const [
            BoxShadow(
              color: Color(0x19000000),
              blurRadius: 3.05,
              offset: Offset(1.72, 1.72),
              spreadRadius: 0,
            ),
            BoxShadow(
              color: Color(0x19000000),
              blurRadius: 1.38,
              offset: Offset(-1.72, -1.72),
              spreadRadius: 0,
            )
          ],
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Text(
              text,
              textAlign: TextAlign.center,
              style: TextStyle(
                color: text == '分享' ? Colors.white : Color(0xFF303030),
                fontSize: 15,
                fontFamily: 'Inter',
                fontWeight: FontWeight.w400,
                height: 1.02,
              ),
            ),
          ],
        ),
      ),
      onTap: () {
        callback();
      },
    );
  }

  Widget dataListBuild(index) {
    return Column(children: [
      for (int subIndex = 0;
          subIndex < dataList[index]['stepList'].length;
          subIndex++)
        contentBuild(task, subIndex, dataList[task]['stepList'][subIndex]),
    ]);
  }

  @override
  Widget build(BuildContext context) {
    int index = 0;
    print('task$task');
    return SingleChildScrollView(
      child: Stack(
        children: [
          Container(
            height: 660,
            child: Padding(
              padding: EdgeInsets.all(24),
              child: Column(
                children: [
                  headTitle(),
                  if (dataList.isNotEmpty) dataListBuild(index),
                  // 添加任务
                  // if (!isOver)
                  //   GestureDetector(
                  //     child: Image.asset(
                  //       'lib/assets/images/home/track/arrow_right.png',
                  //       width: 82,
                  //       height: 82,
                  //     ),
                  //     onTap: () {
                  //       setState(() {});
                  //       List list = dataList[task]['stepList'];
                  //       dataList[task]['stepList'].add({
                  //         'text': '',
                  //         'status': '1', // 1未完成 2已完成,
                  //         'id': list[list.length - 1]['id'] + 1,
                  //         'taskId': "${dataList[task][0]['taskId']}"
                  //       });
                  //     },
                  //   ),
                  // isOver
                  // if (isOver)
                  // Column(
                  //   children: [
                  //     SizedBox(height: 60),
                  //     buttonBuild('分享', () {
                  //       EasyLoading.showToast('分享成功！');
                  //     }),
                  //     SizedBox(height: 16),
                  //     buttonBuild('收藏', () {
                  //       EasyLoading.showToast('收藏成功！');
                  //     }),
                  //     SizedBox(height: 16),
                  //     buttonBuild('返回列表', () {
                  //       widget.callBack({'type': 'back'});
                  //     }),
                  //   ],
                  // ),
                  // 进度100% 按钮
                  // TextButton(
                  //     onPressed: () {
                  //       // 进度改为100%
                  //       print(
                  //           '当前任务数量dataList${dataList[task]['stepList'].length}');
                  //       progress = dataList[task]['stepList'].length;
                  //       // 显示收藏&分享&返回列表
                  //       isOver = true;
                  //       setState(() {});
                  //     },
                  //     child: Text('任务全部完成'))
                ],
              ),
            ),
          ),
          Positioned(
              top: 490,
              right: 14,
              child: Row(
                children: [
                  if (isNeedRemind)
                    GestureDetector(
                      child: Container(
                        padding: const EdgeInsets.symmetric(
                            vertical: 10, horizontal: 16),
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                            color: Color.fromRGBO(223, 30, 0, 0.6),
                            borderRadius: BorderRadius.circular(30)),
                        child: Text(
                          '请填写本周情况',
                          style: TextStyle(
                              fontSize: 13, color: hexColor('#ffffff')),
                        ),
                      ),
                      onTap: () {
                        widget.callBack();
                      },
                    ),
                  SizedBox(width: 6),
                  GestureDetector(
                    child: Container(
                      padding: const EdgeInsets.symmetric(
                          vertical: 10, horizontal: 16),
                      height: 60,
                      width: 60,
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                          color: isNeedRemind
                              ? Color.fromRGBO(223, 30, 0, 0.6)
                              : Color.fromRGBO(161, 161, 161, 0.5),
                          borderRadius: BorderRadius.circular(30)),
                      child: Text(
                        '情绪报告',
                        style:
                            TextStyle(fontSize: 13, color: hexColor('#ffffff')),
                      ),
                    ),
                    onTap: () {
                      widget.callBack();
                    },
                  ),
                ],
              )),
          Positioned(
              top: 590,
              left: 54,
              // right: 24,
              child: Container(
                padding: EdgeInsets.only(right: 12),
                height: 24,
                width: 310,
                alignment: Alignment.centerRight,
                decoration: BoxDecoration(
                    border: Border.all(width: 1.px, color: hexColor('#cccccc')),
                    borderRadius: BorderRadius.circular(16)),
                child: Text(
                    '${progress()}/${dataList.isNotEmpty ? dataList[task]['stepList'].length : 0}',
                    style: TextStyle(color: hexColor('#666666'))),
              )),
          Positioned(
              top: 592,
              left: 52,
              child: Container(
                height: 20,
                width: dataList.isNotEmpty
                    ? ((310 / (dataList[task]['stepList'].length))) * progress()
                    : 0,
                decoration: BoxDecoration(
                  color: hexColor('#E9614D'),
                  borderRadius: BorderRadius.circular(20),
                ),
              )),
          Positioned(
              top: 556,
              left: 20,
              right: 24,
              child: Row(
                children: [
                  Image.asset(
                    'lib/assets/images/home/genertate/progress.png',
                    width: 52,
                    height: 62,
                  ),
                ],
              ))
        ],
      ),
    );
  }
}

class ShadowedRectangularTrackShape extends SliderTrackShape {
  final double shadowBlur;
  final Color shadowColor;

  const ShadowedRectangularTrackShape({
    this.shadowBlur = 3.0,
    this.shadowColor = const Color.fromRGBO(0, 0, 0, 0.1),
  });

  @override
  Rect getPreferredRect({
    required RenderBox parentBox,
    Offset offset = Offset.zero,
    required SliderThemeData sliderTheme,
    bool isEnabled = false,
    bool isDiscrete = false,
  }) {
    // 计算轨道尺寸（高度10px，宽度占满父容器）
    final trackHeight = sliderTheme.trackHeight ?? 10.0;
    final trackLeft = offset.dx;
    final trackTop = offset.dy + (parentBox.size.height - trackHeight) / 2;
    final trackWidth = parentBox.size.width;
    return Rect.fromLTWH(trackLeft, trackTop, trackWidth, trackHeight);
  }

  @override
  void paint(
    PaintingContext context,
    Offset offset, {
    required RenderBox parentBox,
    required SliderThemeData sliderTheme,
    required Animation<double> enableAnimation,
    required TextDirection textDirection,
    required Offset thumbCenter,
    Offset? secondaryOffset,
    bool isDiscrete = false,
    bool isEnabled = false,
  }) {
    final canvas = context.canvas;
    final trackRect = getPreferredRect(
      parentBox: parentBox,
      offset: offset,
      sliderTheme: sliderTheme,
      isEnabled: isEnabled,
      isDiscrete: isDiscrete,
    );
    final shadowPaint = Paint()
      ..color = shadowColor
      ..maskFilter = MaskFilter.blur(BlurStyle.normal, shadowBlur);
    canvas.drawRRect(
      RRect.fromRectAndRadius(trackRect, Radius.circular(12)),
      shadowPaint,
    );

    // 2. 绘制轨道背景（白色）
    final inactivePaint = Paint()..color = sliderTheme.inactiveTrackColor!;
    canvas.drawRRect(
      RRect.fromRectAndRadius(trackRect, Radius.circular(12)),
      inactivePaint,
    );

    final activeRect = Rect.fromLTWH(
      trackRect.left,
      trackRect.top,
      thumbCenter.dx - trackRect.left, // 激活部分宽度随滑块位置变化
      trackRect.height,
    );
    final activePaint = Paint()..color = sliderTheme.activeTrackColor!;
    canvas.drawRRect(
      RRect.fromRectAndRadius(activeRect, Radius.circular(12)),
      activePaint,
    );
  }
}

class CustomRectangularThumbShape extends SliderComponentShape {
  final double width;
  final double height;
  final double shadowBlur;
  final Color shadowColor;

  const CustomRectangularThumbShape({
    this.width = 12.0,
    this.height = 26.0,
    this.shadowBlur = 4.0,
    this.shadowColor = const Color.fromRGBO(0, 0, 0, 0.2),
  });

  @override
  Size getPreferredSize(bool isEnabled, bool isDiscrete) {
    return Size(width, height + shadowBlur);
  }

  @override
  void paint(
    PaintingContext context,
    Offset center, {
    required Animation<double> activationAnimation,
    required Animation<double> enableAnimation,
    required bool isDiscrete,
    required TextPainter labelPainter,
    required RenderBox parentBox,
    required SliderThemeData sliderTheme,
    required TextDirection textDirection,
    required double value,
    required double textScaleFactor,
    required Size sizeWithOverflow,
  }) {
    final canvas = context.canvas;
    final rect = Rect.fromCenter(
      center: center,
      width: width,
      height: height,
    );

    // 绘制滑块阴影
    final shadowPaint = Paint()
      ..color = shadowColor
      ..maskFilter = MaskFilter.blur(BlurStyle.normal, shadowBlur);
    canvas.drawRect(rect.shift(Offset(0, 2)), shadowPaint);

    // 绘制滑块本体
    final thumbPaint = Paint()..color = sliderTheme.thumbColor!;
    canvas.drawRect(rect, thumbPaint);
  }
}
